package LopCoBan;
import javax.swing.JOptionPane;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;


public class CoSoDuLieu {

	private static String DB4OFILENAME = "database1.db4o";
	public static ObjectContainer dulieu = null;
	
	public static void KetNoiDuLieu()
	{
		try {
		dulieu = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), DB4OFILENAME);
		
	//	JOptionPane.showConfirmDialog(null, "Da ket noi du lieu thanh cong",
	//				DB4OFILENAME, JOptionPane.ERROR_MESSAGE);
		}
		catch (Exception e) {
	        throw e;
	    } finally {
	   
	      
	    }
	}
	//Them
	public static void ThemDuLieu(Object object)
	{
		dulieu.store(object);
	}
	//select
	public static <TargetType> ObjectSet LayDuLieu(java.lang.Class<TargetType> clazz, String dieuKien, String giatri)
	{
		Query query= dulieu.query();
		query.constrain(clazz);
		query.descend(dieuKien).constrain(giatri);		    
		return query.execute();
	}
	public static <TargetType> ObjectSet LayDuLieu(java.lang.Class<TargetType> clazz)
	{
		Query query= dulieu.query();
		query.constrain(clazz);		
		return query.execute();
	}
	//kiem tra trung
	public static <TargetType> boolean KiemTraTrung(java.lang.Class<TargetType> clazz, String dieuKien, String giatri)
	{
		ObjectSet<TargetType> list = CoSoDuLieu.LayDuLieu(clazz, dieuKien, giatri);
		return (list.size() == 0);
	}
	//xoa
	public static <TargetType> boolean XoaDuLieu(java.lang.Class<TargetType> clazz, String dieuKien, String giatri)
	{
		Query query= dulieu.query();
		query.constrain(clazz);
		query.descend(dieuKien).constrain(giatri);		    
		ObjectSet list = query.execute();
		if (list.size() == 0)
			return false;
		else 
			dulieu.delete(list.next());
		return true;
	}
	//sua
	public static <TargetType> boolean CapNhatDuLieu(java.lang.Class<TargetType> clazz, String dieuKien, String giatri, Object newObj)
	{
		Query query= dulieu.query();
		query.constrain(clazz);
		query.descend(dieuKien).constrain(giatri);		    
		ObjectSet list = query.execute();
		if (list.size() == 0)
			return false;
		else 
		{
			dulieu.delete(list.next());
			dulieu.store(newObj);
		}
		return true;
	}
	
	public static void DongKetNoi()
	{
		dulieu.close();
	}
}
